<template>
	<div class="bannerdata">
		<div style="text-align: left;"><span>组件名称：</span>广告轮播图组件</div>
		<blue-button text="新增" :clickEvent="addClickEvent" class="add-btn" style="float: left;">
		</blue-button>
		<blue-button text="一键纠正" v-if="sortCorrectshow" :clickEvent="enitClickEvent" class="add-btn" style="float: right;">
		</blue-button>
		<table class="sv-table">
			<tr class="table-th">
				<th>序号</th>
				<th>资源名称</th>
				<th>跳转路径</th>
				<th>生效时间</th>
				<th>失效时间</th>
				<th>状态</th>
				<th>操作</th>
				<th>排序</th>
			</tr>
			<tr class="table-tr" v-for="(item, index) in getDataArray" :key="index">
				<td>{{item.sortNo}}</td>
				<td><span>{{item.relTitle}}</span></td>
				<td>{{urlfn(item)}}</td>
				<td>{{item.showTime | startTime}}</td>
				<td>{{item.expireDate | endTime}}</td>
				<td><span :class="[item.status == '1' && !( item.expireDate && item.expireDate < new Date().getTime())? 'banner-qiyong' : 'banner-tingyong']">{{isShow(item) ? "已启用" : "已停用"}}</span></td>
				<td class="handle-button" ref="handleButton">
					<gray-button text="编辑" :clickEvent="editClickEvent.bind(this, index)"></gray-button>
					<gray-button :text="item.status  == '1' && !( item.expireDate && item.expireDate < new Date().getTime()) ? '停用' : '启用'" :clickEvent="enableClickEvent.bind(this, item.rid, item.status,index,item)"></gray-button>
					<gray-button text="删除" :disabled="item.status == '1' && !( item.expireDate && item.expireDate < new Date().getTime())" :clickEvent="deleteClickEvent.bind(this, item.rid,item.status)"></gray-button>
				</td>
				<td v-if="getDataArray.length>0"><span v-if="index!=0" class="sortspan" @click="sort(item,'-1',index)">↑</span><span v-if="index!=getDataArray.length-1" class="sortspan" @click="sort(item,'1',index)">↓</span></td>
			</tr>
		</table>
		<div class="bannerstyle">
			<span>滑动方式：</span>
			<div class="banneranim" v-for="(item, index) in SelectedStatedata" :key="index">
				<cirle-select class="stylename" :state="item.index == activeIndex" :clickEvent="CirleSelectedState.bind(this, item.index)"></cirle-select><span>{{item.text}}</span>
			</div>
		</div>

		<!-- 编辑或新增的弹框 -->
		<edit-model ref="editModel" title="Banner位配置" :closeCallback="editModelCloseEvent">
			<div class="slot-banner" slot="main">
				<div v-if="handleType === 'edit'">
					<p class="eidt-slot-title">资源位</p><input type="text" :value="getDataItem.rid" disabled/>
				</div>
				<div>
					<span class="eidt-slot-title">资源标题<span class="required">*</span></span><input type="text" v-model="getDataItem.relTitle" /></div>
				<div>
					<span class="eidt-slot-title">生效日期<span class="required">*</span></span>
					<el-date-picker v-model="startTime" type="datetime" placeholder="选择日期时间" style="border: none;width: 350px;">
					</el-date-picker>
				</div>
				<div v-if="handleType === 'add'">
					<span class="eidt-slot-title">失效日期<span class="required">*</span></span>
					<el-date-picker v-model="endTime"  :default-value="endTimeAdd" type="datetime" placeholder="选择日期时间" style="border: none;width: 350px;">
					</el-date-picker>
				</div>
				<div v-if="handleType === 'edit'">
					<span class="eidt-slot-title">失效日期<span class="required">*</span></span>
					<el-date-picker v-model="endTime" type="datetime" placeholder="选择日期时间" style="border: none;width: 350px;">
					</el-date-picker>
				</div>

				<div>
					<span class="eidt-slot-title">图片上传<span class="required">*</span></span>
					<div class="upload-box">
						<img-upload ref="bannerImg" :deleteCallback="bannerDeleteCallback" :imgShowList="getDataItem.publicityPicture ? [getDataItem.publicityPicture] : []">
						</img-upload>
					</div>
				</div>
				<div>
					<p class="eidt-slot-title" style="width: 23%;">自定义跳转链接</p>
					<page-path :changeEvent="changeEvent" :defaultChooseProps="valueArray" rootSelector="#edit-model-box"></page-path>
				</div>
				<div class="fabu-box">
					<blue-button text="发布" :clickEvent="submitClickEvent"></blue-button>
				</div>
			</div>
			<div slot="slide">
				<search-product ref="searchModel" @getgoodscodedata="getgoodscode"></search-product>
			</div>
		</edit-model>
		<m-toast ref="toast"></m-toast>
		<m-dialog ref="dialog"></m-dialog>
	</div>

</template>

<script>
	import BlueButton from "../../edit-components/BlueButton";
	import SearchProduct from "../../edit-components/SearchProduct";
	import CirleSelect from "../../edit-components/CirleSelect";
	import GrayButton from "../../edit-components/GrayButton";
	import EditModel from "../../edit-components/EditModel";
	import getData from './getData';
	import sortCorrect from './sortCorrect';
	import enableOdisable from "./enableOdisable";
	import publish from "./editOAdd";
	import enableSort from "./enableSort";
	import deleteFn from "./delete";
	import add from "./add";
	import { DatePicker } from "element-ui";
	import imgUpload from "../../real-components/ImgUpload2";
	import Toast from "../../edit-components/Toast";
	import Dialog from "../../edit-components/Dialog";
	import Validator from "../../utils/validator";
	import { getPageNameOrVirtualPageName } from "../../utils/getPageName";
	import PagePath from "../../edit-components/PagePath";

	export default {
		props: {
			config:{
				type:Object,
				default: ()=>{}
			}
		},
		data() {
			return {
				dataArray: [],
				dataItem: null,
				params: {},
				type: null, //推广类型默认商品=0，活动=1
				startTime: "",//生效时间
				bannerUrl: "", //用于上传的banner图片
				activePicture: "", //用于上传的活动图片
				handleType: "add",
				SelectedStatedata: [{
					index: 0,
					text: "左右滑动"
				}, {
					index: 1,
					text: "淡入淡出"
				}],
				activeIndex: 0,
				goodscodedata: "",
				//门店信息
				storeCode: "",
				selected: "",
				valueArray: [],
				sortCorrectshow:false,
				endTime:''
			}
		},
		components: {
			"blue-button": BlueButton,
			"search-product": SearchProduct,
			"cirle-select": CirleSelect,
			"gray-button": GrayButton,
			"edit-model": EditModel,
			"el-date-picker": DatePicker,
			"img-upload": imgUpload,
			"m-toast": Toast,
			"m-dialog": Dialog,
			"page-path": PagePath,
		},
		computed: {
			pageName() {
				return getPageNameOrVirtualPageName();
			},
			getDataArray() {
				return this.dataArray;
			},
			//获得选中的数据item
			getDataItem() {
				if(this.dataItem) {
					return this.dataItem;
				}
				return {};
			},
			getBannerUrl() {
				return this.bannerUrl;
			},
			relGroup(){
				return this.config.id
			},
			part() {
				return this.$store.getters['gw/getEditComponentsList'][0].part
			},
			endTimeAdd:{
				get:function(){
					let date = this.startTime;
					let defaultEndTime = new Date(date).setUTCDate(new Date(date).getUTCDate() + 7);
					return defaultEndTime
				},
				set: function () {}
			}
		},
		methods: {
			//排序
			sort(item, num, index) {
				var sortnum
				var direction
				if(index == 0 && num == -1) {
					sortnum = this.getDataArray.length-1
				} else if(index == this.getDataArray.length - 1 && num == 1) {
					sortnum = 0
				} else {
					sortnum = Number(index) + Number(num)
				}
				if(num==1){
					direction = 'DESC'
				}else if(num==-1){
					direction = 'ASC'
				}
				this.params = {
					rid: item.rid,
					targetRid: this.getDataArray[sortnum].rid,
					direction: direction,
					storeCode: item.storeCode,
					relGroup:item.relGroup
				}
				let callback = (data) => {
					this.dataArray = data;
				}
				let errFn = (data) => {
					this.$refs.toast.toast(data);
				}
				enableSort(this.params, item.relGroup, callback, errFn);
			},
			//一键纠正
			enitClickEvent(){
				let callback = (data) => {
					this.dataArray = data;
				}
				let errFn = (data) => {
					this.$refs.toast.toast(data);
				}
				sortCorrect(this.relGroup, callback, errFn);
			},
			//一键纠正显示隐藏
			sortCorrectshowfn(){
				var sortCorrectnum=[]
				for(var i=0;i<this.getDataArray.length;i++){
					sortCorrectnum.push(this.getDataArray[i].sortNo)
				}
				var nary=sortCorrectnum.sort()
				for(var j=0;j<nary.length;j++){
					if(nary[j]==nary[j+1]){
						this.sortCorrectshow = true
						return
					}
				}
			},
			//获取子组件路径的值
			changeEvent(data) {
				this.selected = data
			},
			//路径地址展示
			urlfn(item) {
				if(item.extendField && JSON.parse(item.extendField).url) {
					return JSON.parse(item.extendField).url.UIContent
				} else {
					return "--"
				}
			},
			//获取门店code
			getShopCode() {
				this.storeCode = localStorage.getItem("storeCode");
			},
			//模态框关闭后的回调事件
			editModelCloseEvent() {
				//this.getBannerData()
			},
			getBannerData() {
				let callback = (data) => {
					this.dataArray = data;
					console.log("banner图的配置数据", data);
				}
				getData(callback, this.relGroup);
			},
			/*获取商品编码*/
			//显示侧滑栏查找商品编码
			showMenu() {
				this.$refs.editModel.showSlideMenu();
				this.$refs.searchModel.hideModel();
			},
			getgoodscode(msg) {
				this.goodscodedata = msg;
			},
			//获取推广类型
			promotionTypedata(item) {
				if(item.promotionType == 1) {
					return "商品"
				} else if(item.promotionType == 2) {
					return "活动"
				} else if(item.promotionType == 3) {
					return "分类"
				} else {
					return ""
				}
			},
			//新增按钮的事件
			addClickEvent() {
				if(!getCookie("sessionId")){
				this.$refs.toast.toast("登录失效，请重新登录");
				return
			    }
				this.handleType = "add";
				this.$refs.editModel.showCover();
				// let item = this.getDataItem(index);
				this.dataItem = [];
				this.startTime = "";
				this.endTime = "";
				this.selected = "";
				this.goodscodedata = "";
				//this.type = 0;
				this.bannerUrl = "";
				this.valueArray = []
				this.selected = ""
				/*document.querySelectorAll("input[name=tuiguang]")[0].checked = true;*/
				if(this.$refs.bannerImg) {
					this.$refs.bannerImg.deleteImg();
				}
				if(this.$refs.activityImg) {
					this.$refs.activityImg.deleteImg();
				}
			},
			//编辑按钮的事件
			editClickEvent(index) {
				this.handleType = "edit";
				//显示cover
				this.$refs.editModel.showCover();
				// let item = this.getDataItem(index);
				this.dataItem = this.getDataItemFn(index);
				//标题
				/*this.getDataItem = this.getDataItemFn(index)*/
				//初始化主图
				this.bannerUrl = this.dataItem.publicityPicture;
				// console.log(this.bannerUrl);
				//初始化生效时间
				this.startTime = this.dataItem.showTime;
				//初始化失效时间
				this.endTime = this.dataItem.expireDate;
				//初始化推广类型
				//this.type = this.dataItem.promotionType - 1;
				/*setTimeout(() => {
					document.querySelectorAll("input[name=tuiguang]")[this.type].checked = true;
				},300)*/
				//分类编码 商品编码 
				if(this.type == 0) {
					this.goodscodedata = this.dataItem.goodsCode
				} else if(this.type == 2) {
					this.selected = this.dataItem.goodsCode
				}
				//初始化商品编码或者活动图片
				this.activePicture = this.dataItem.activePicture;
				if(this.dataItem.extendField) {
					this.valueArray = JSON.parse(this.dataItem.extendField).url.valueArray
					this.selected = JSON.parse(this.dataItem.extendField).url
				}
				// console.log("this.dataItem.activityPicture", this.dataItem.activePicture)

			},
			//发布按钮的点击事件
			async submitClickEvent() {
				//上传图片
				//商品推广
				/*if(this.type === 0 || this.type === 2) {*/
				let response = await this.$refs.bannerImg.upload();
				if(response.status === 0) {
					this.errorToast("图片上传失败");
					return;
				}
				if(response.status === 2) {
					if(!this.bannerUrl) {
						this.errorToast("未上传图片");
						return;
					}
				}
				if(response.status === 1) {
					this.bannerUrl = response.data[0];
					console.log(this.bannerUrl);
				}
				this.publishFn();
			},
			//停用/启用按钮的事件
			enableClickEvent(rid, status,index,item) {
				if (item.expireDate && (item.expireDate < new Date().getTime())) {
					this.editClickEvent(index)
					this.$refs.toast.toast("失效时间已经过期，请重新设置失效时间");
				}else{
					let msg = status == "2" ? "启用" : "停用";
					let msgss = `确定要${msg}该资源位吗？`;
					let toastmsg1 = `该资源位${msg}成功`;
					let toastmsg2 = `该资源位${msg}失败`;
					let confirmFn = () => {
						status = status == "1" ? "2" : "1";
						let params = {
							rid: rid,
							status: status,
							storeCode: this.storeCode,
							relGroup: this.relGroup,
						}
						let callback = (data) => {
							this.dataArray = data;
							this.$refs.toast.toast(toastmsg1);
						}
						let errFn = (data) => {
							this.$refs.toast.toast(toastmsg2);
						}
						enableOdisable(params, this.relGroup, callback, errFn);
					}
					this.infoDialog(msgss, confirmFn);
					}
			},
			//删除按钮的事件
			deleteClickEvent(id, status) {
				let msg = "确定要删除该资源位吗？";
				let confirmFn = () => {
					let params = {
						rid: id,
						storeCode: this.storeCode,
						relGroup: this.relGroup
					}
					let callback = data => {
						this.dataArray = data;
						this.$refs.toast.toast("删除成功");
					}
					let errFn = (data) => {
						this.$refs.toast.toast(data);
					}
					deleteFn(params, this.relGroup, callback, errFn);
				}
				this.infoDialog(msg, confirmFn);
			},
			publishFn() {
				this.getParams();
				//校验参数的完整性
				console.log(this.params);
				/*return;*/
				//检验relTitle
				if(!this.params.relTitle) {
					this.$refs.toast.toast("资源标题不能为空");
					return;
				}
				//生效时间
				if(!this.startTime) {
					console.log("打印生效时间",this.startTime)
					this.$refs.toast.toast("生效时间不能为空");
					return;
				}
				if(!this.endTime) {
					this.$refs.toast.toast("失效时间不能为空");
					return;
				}
				if(this.endTime < this.startTime){
					this.$refs.toast.toast("失效时间不能早于生效时间");
					return;
				}
				if(this.endTime< new Date().getTime()){
					this.$refs.toast.toast("失效时间不能早于当前时间");
					return;
				}
				//检验主图
				if(!this.params.publicityPicture) {
					this.$refs.toast.toast("请上传图片");
					return;
				}
				//检测商品编码
				if(!this.goodscodedata && this.type === 0) {
					this.$refs.toast.toast("商品编码不能为空");
					return;
				}
				//推广图片
				if(!this.params.activePicture && this.type === 1) {
					this.$refs.toast.toast("推广图片不能为空");
					return;
				}
				//检测分类编码
				if(!this.selected && this.type === 2) {
					this.$refs.toast.toast("分类编码不能为空");
					return;
				}
				let callback = (data) => {
					this.$refs.toast.toast("发布成功");
					this.dataArray = data;
					this.$refs.editModel.hideCover();
					this.valueArray = [this.selected]
				}
				let errFn = (data) => {
					this.$refs.toast.toast(data);
				}
				if(this.handleType === "edit") {
					publish(this.params, this.relGroup, callback, errFn);
				} else if(this.handleType === "add") {
					add(this.params, this.relGroup, callback, errFn);
				}

			},
			//格式化发布的参数
			getParams() {
				//判断参数
				var obj = {
					"url": this.selected
				}
				var str = JSON.stringify(obj);
				let typedata = Number(this.type) + 1
				this.params = {
					storeCode: this.storeCode,
					status: this.getDataItem.status || "2",
					//promotionType: typedata, //商品是1，活动是2，
					relTitle: this.getDataItem.relTitle,
					publicityPicture: this.getBannerUrl,
					relGroup: this.relGroup,
					extendField: str,
				}
				if(this.handleType === "edit") {
					this.params = Object.assign({}, this.params, {
						rid: this.getDataItem.rid,
					});
				}
				if(this.startTime) {
					let date = new Date(this.startTime);
					let showTime = `${date.getFullYear()}-${date.getMonth() + 1 > 9 ? date.getMonth() + 1:'0' + (date.getMonth() + 1)}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
					this.params = Object.assign({}, this.params, {
						showTime: showTime,
					});
				} else {
					this.params = Object.assign({}, this.params, {
						showTime: "",
					});
				}
				//设置失效时间的参数
				if(this.endTime) {
					let date = new Date(this.endTime);
					let expireDate = `${date.getFullYear()}-${date.getMonth() + 1 > 9 ? date.getMonth() + 1:'0' + (date.getMonth() + 1)}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
					this.params = Object.assign({}, this.params, {
						expireDate: expireDate,
					});
				} else {
					this.params = Object.assign({}, this.params, {
						expireDate: "",
					});
				}

				//配置商品编码或者活动图片
				if(this.type === 0) {
					//配置商品编码
					this.params.goodsCode = this.goodscodedata;
				} else if(this.type === 1) {
					//配置活动图片
					this.params.activePicture = this.activePicture;
				} else if(this.type === 2) {
					//配置分类编码
					this.params.goodsCode = this.selected;
				}
				/* else {
									return;
								}*/
				console.log("这是要上传的params", this.params);
			},
			//返回对应index的数据
			getDataItemFn(index) {
				return this.dataArray[index];
			},
			// 切换商品还是活动
			changeType(type) {
				this.$refs.editModel.hideMenu();
				this.type = type;
				/*if(this.type == 1 || this.type == 2) {
					this.$refs.searchModel.hideModel();
				}*/
			},
			errorToast(msg, duration = 1000) {
				this.$refs.toast.toast(msg, duration);
			},
			infoDialog(msg, confirmFn) {
				this.$refs.dialog.dialog({
					msg,
					confirmFn
				});
			},
			//插件那边删除图片，这边也要删除图片
			bannerDeleteCallback() {
				console.log("删除对应的图片");
				this.bannerUrl = "";
			},
			activityDeleteCallback() {
				this.activePicture = "";
			},
			CirleSelectedState(index) {
				this.activeIndex = index;
				this.setEditConfigNew(this.relGroup, {
					bannerAnimation: this.activeIndex + ""
				}, this.part);
			},
			echo() {
				if(this.getCurrentVDONew(this.relGroup,  this.part).config.bannerAnimation === undefined) {
					this.setEditConfigNew(this.relGroup, {
						bannerAnimation: this.activeIndex + ""
					}, this.part)
				} else {
					this.activeIndex = this.getCurrentVDONew(this.relGroup, this.part).config.bannerAnimation;
				}
			},
			isShow(item){
				if(item.status == "1" && ! (item.expireDate && (item.expireDate < new Date().getTime()))){
					return true
				}else{
					return false
				}
			}
		},
		filters: {
			startTime: function(time) {
				if(time) {
					let date = new Date(time);
					return `${date.getFullYear()}-${date.getMonth() + 1 > 9 ? date.getMonth() + 1:'0' + (date.getMonth() + 1)}-${date.getDate()> 9 ? date.getDate() : '0' + date.getDate()}  ${date.getHours() > 9 ? date.getHours() : '0' + date.getHours()}:${date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()}`;
				} else {
					return "--"
				}

			},
			endTime: function(time) {
				if(time) {
					let date = new Date(time);
					return `${date.getFullYear()}-${date.getMonth() + 1 > 9 ? date.getMonth() + 1:'0' + (date.getMonth() + 1)}-${date.getDate()> 9 ? date.getDate() : '0' + date.getDate()}  ${date.getHours() > 9 ? date.getHours() : '0' + date.getHours()}:${date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()}`;
				} else {
					return "--"
				}

			}
		},
		created() {
			
		},
		mounted() {
			if(!getCookie("sessionId")){
				this.$refs.toast.toast("登录失效，请重新登录");
			}
			this.getBannerData();
			this.$nextTick(() => {
				this.echo();
			})
			this.getShopCode()
			this.sortCorrectshowfn()
		},
		watch: {
			dataArray(newVal) {
				this.sortCorrectshowfn()
			},
			relGroup(newVal) {
				console.log('22222222222')
				this.getBannerData();
				this.getShopCode();
				this.echo();
			}
		}

	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
	.add-btn {
		margin-bottom: 10px;
		display: inline-block;
	}
	
	.handle-button>div {
		margin: 0 1px;
		padding: 8px 0px;
	}
	
	.banner-edit-box {
		position: fixed;
		left: 0;
		top: 0;
	}
	
	.edit-cover {
		position: absolute;
		left: 0;
		top: 0;
		background: #000;
		width: 100%;
		height: 100%;
		opacity: 0;
		transition: opacity 0.3s;
	}
	
	.edit-content {
		background: #fff;
		width: 600px;
		height: 300px;
		position: absolute;
		left: 0;
		right: 0;
		border-radius: 3px;
		margin: auto;
		transform: translateY(-300px);
		transition: transform 0.3s ease-out;
	}
	
	.edit-title-box {
		display: flex;
		box-sizing: border-box;
		padding: 15px;
		width: 100%;
		height: 60px;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #ddd;
	}
	
	.edit-close {
		font-size: 20px;
		font-weight: bold;
		color: #ddd;
		cursor: pointer;
	}
	
	.edit-close:hover {
		color: #444;
	}
	/* 编辑区域的样式 */
	
	.slot-banner>div {
		display: flex;
		margin-bottom: 10px;
		align-items: center;
	}
	
	.slot-banner>div input[type=radio] {
		width: unset;
	}
	
	.el-date-editor {
		width: 50%;
		border: 1px solid #ddd;
		height: 28px;
	}
	
	.el-date-editor input {
		height: 28px;
	}
	
	.el-input__inner {
		height: 28px !important;
	}
	
	.upload-box {
		border: 1px solid #ddd;
	}
	
	.banner-qiyong {
		background-color: #2980b9;
		color: #fff;
		font-size: 12px;
		border-radius: 3px;
		padding: 1px;
	}
	
	.banner-tingyong {
		background-color: #e74c3c;
		color: #fff;
		font-size: 12px;
		border-radius: 3px;
		padding: 1px;
	}
	
	.fabu-box {
		display: flex;
		justify-content: center;
		margin-top: 30px;
	}
	
	.bannerstyle {
		text-align: left;
		margin-top: 25px;
	}
	
	.bannerstyle .stylename {
		display: inline-block;
		vertical-align: middle;
		margin: 0px 15px;
	}
	
	.bannerstyle .banneranim {
		display: inline-block;
		margin-right: 15px;
	}
	
	.bannermySelect {
		border: 1px solid #ddd;
		padding: 5px 5px;
		width: 50%;
		height: unset;
		margin-bottom: 10px;
	}
	
	.bannerdata tr td:nth-child(2) span {
		display: inline-block;
		width: 88px;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
	
	.bannerdata tr td:last-child span {
		color: red;
	}
	
	.sortspan {
		display: inline-block;
		width: 20px;
	}
</style>